package com.haochang.chunkvod.controller.activity.hostess;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.adapter.hostess.SortRoomRoomAdapter;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.model.hostess.HostessInfo;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.view.vod.listView.DragSwapListView;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

/**
 * @author Yangjie
 *         className ReserveActivity
 *         created at  2016/8/23  18:08
 *         咨客 开房排序 房间层排序
 */
public class SortRoomSecondActivity extends BaseActivity implements SortRoomRoomAdapter.PositionChangedCallBack
{
	private TitleView titleView;
	private BaseTextView tv_area;//1区，2区
	private DragSwapListView lv_sort_room;//拖动换位listview
	private BaseTextView tv_sort;

	private SortRoomRoomAdapter adapter;
	private List<HostessInfo> listRoomInfo = new ArrayList<HostessInfo>();
	private int sortType;//排序类型，0默认不能拖动排序(可置顶，置底)，1激活排序功能 ,2置顶，置底有数据变换时，显示完
	private String areaId, roomName;
	private JSONArray jsonArray;
	private HostessData hostessData;

	@Override
	public void receiveParam()
	{
		areaId = getIntent().getStringExtra(IntentKey.SORT_ROOM_AREA_ID);
		roomName = getIntent().getStringExtra(IntentKey.SORT_ROOM_NAME);
		try
		{
			jsonArray = new JSONArray(getIntent().getStringExtra(IntentKey.JSONArray));
			Logger.e(areaId);
			Logger.e(jsonArray.toString());
		} catch (Exception e)
		{
			Logger.e("咨客按房型排序_接受参数：" + e.getMessage());
		}
	}

	@Override
	public void initData()
	{
		hostessData = new HostessData(SortRoomSecondActivity.this);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_sort_room_area);
		tv_sort = (BaseTextView) findViewById(R.id.tv_sort);
		lv_sort_room = (DragSwapListView) findViewById(R.id.lv_sort_room);
		tv_area = (BaseTextView) findViewById(R.id.tv_area);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(R.string.sort_room).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				if (adapter.hasDataChanged())
				{
					showPopSave();
				} else
				{
					finish();
					animRightToLeft();
				}
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("回到首页");
				list.add("修改密码");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(SortRoomSecondActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							backToHome();
							break;
						case 1:
							goToPasswordModify();
							break;
						case 2:
							loginOut();
							break;

						default:
							break;
						}
					}
				});
			}
		});

	}

	@Override
	public void initViewsData()
	{
		tv_area.setText(String.valueOf("房间" + "(" + roomName + ")"));
		tv_sort.setOnClickListener(clickSortListner);
		initIntentData();
	}

	OnBaseClickListener clickSortListner = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			if (sortType == 0)
			{
				sortType = 1;
				//正常--排序
				//启动排序
				tv_sort.setText(R.string.complete);
				lv_sort_room.setCanDrag(true);
				adapter.setCanExpand(false);
				for (HostessInfo info : listRoomInfo)
				{
					info.setShowBottom(false);
					info.setShowRightDrawable(true);
				}
				adapter.notifyDataSetChanged();
			} else if (sortType == 1)
			{
				//正常--排序--完成
				//排序完成
				//请求保存开房排序
				requestSaveSortRoomRoom(1);
			} else if (sortType == 2)
			{
				//正常--置顶/置底--完成
				//点击完成保存置底置顶信息
				//请求保存开房排序
				requestSaveSortRoomRoom(2);
			}
		}
	};

	/**
	 * 在initview之后初始化数据
	 */
	private void initIntentData()
	{
		if (!TextUtils.isEmpty(areaId))
		{
			if (jsonArray != null && jsonArray.length() > 0)
			{
				int length = jsonArray.length();
				for (int i = 0; i < length; i++)
				{
					JSONObject jsonObject = jsonArray.optJSONObject(i);
					if (null != jsonObject)
					{
						String area_id = jsonObject.optString("area_id");
						if (TextUtils.equals(area_id, areaId))
						{
							JSONArray rooms = jsonObject.optJSONArray("rooms");
							if (rooms != null)
							{
								int length1 = rooms.length();
								for (int j = 0; j < length1; j++)
								{
									JSONObject jsonObject1 = rooms.optJSONObject(j);
									HostessInfo info = new HostessInfo();
									info.setContent(jsonObject1.optString("room_name"));
									info.setRoomId(jsonObject1.optString("room_id"));
									listRoomInfo.add(info);
								}
								if (listRoomInfo.size() > 0)
								{
									adapter = new SortRoomRoomAdapter(SortRoomSecondActivity.this, listRoomInfo, lv_sort_room);
									adapter.setCanExpand(true);
									lv_sort_room.setCanDrag(false);
									lv_sort_room.setAdapter(adapter);
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * created at  2016/8/25  17:18
	 * 保存 开房排序 具体区域的房间顺序
	 * @param sortTypeT 1拖拽排序，2置顶/置底排序
	 */
	private void requestSaveSortRoomRoom(final int sortTypeT)
	{
		JSONArray jsonArrayTranslation = new JSONArray();
		if (jsonArray != null)
		{
			int length = jsonArray.length();
			for (int i = 0; i < length; i++)
			{
				JSONObject jsonObject = jsonArray.optJSONObject(i);
				try
				{
					if (areaId.equals(jsonObject.optString("area_id")))
					{
						JSONObject jsonObject1 = new JSONObject();
						jsonObject1.put("area_id", jsonObject.optString("area_id"));
						jsonObject1.put("area_name", jsonObject.optString("area_name"));
						List<HostessInfo> dataList = adapter.getDataList();
						JSONArray array = new JSONArray();
						if (dataList != null && dataList.size() > 0)
						{
							int le = dataList.size();
							for (int j = 0; j < le; j++)
							{
								JSONObject jsonObject2 = new JSONObject();
								jsonObject2.put("room_id", dataList.get(j).getRoomId());
								jsonObject2.put("room_name", dataList.get(j).getContent());
								array.put(j, jsonObject2);
							}
						}
						jsonObject1.put("rooms", array);
						jsonArrayTranslation.put(i, jsonObject1);
						Logger.e("第二个排序特殊的：" + jsonObject1);
					} else
					{
						jsonArrayTranslation.put(i, jsonObject);
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}

		hostessData.requestSortRoomSave(jsonArrayTranslation, true, new HostessData.ResultResponse()
		{
			@Override
			public void onRequestSuccess()
			{
				ToastUtils.showText(SortRoomSecondActivity.this, "保存开房顺序成功");
				sortType = 0;
				tv_sort.setText(R.string.sort);
				lv_sort_room.setCanDrag(false);
				adapter.setCanExpand(true);
				for (HostessInfo info : listRoomInfo)
				{
					info.setShowBottom(false);
					info.setShowRightDrawable(false);
				}
				if (sortTypeT == 2)
				{
					adapter.notifyDataSetChanged();
				} else if (sortTypeT == 1)
				{
					adapter.notifyDataSetChanged();
				}
				List<HostessInfo> dataList = adapter.getDataList();
				List<HostessInfo> dataListNew = new ArrayList<HostessInfo>();
				if (dataList != null && dataList.size() > 0)
				{
					dataListNew.addAll(dataList);
				}
				adapter.listTemp.clear();
				adapter.listTemp.addAll(dataListNew);
				listRoomInfo.clear();
				listRoomInfo.addAll(dataListNew);
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onFail(int errorNo, String errorMsg)
			{
				ToastUtils.showText(SortRoomSecondActivity.this, "保存开房顺序失败");
			}
		});
	}

	@Override
	public void returnList(List<HostessInfo> list, boolean dataHasChanged)
	{
		if (dataHasChanged)
		{
			sortType = 2;
			tv_sort.setText(R.string.complete);
		} else
		{
			sortType = 0;
			tv_sort.setText(R.string.sort);
		}
	}

	@Override
	public void onBackPressed()
	{
		if (adapter.hasDataChanged())
			showPopSave();
		else
			super.onBackPressed();
	}

	/**
	 * 弹出保存提示框
	 */
	public void showPopSave()
	{
		new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure).cancelable(true)
				.contentName("修改的开房顺序未保存，确定要返回吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
				{
					@Override
					public void onOnlyCancelClick()
					{

					}

					@Override
					public void onOkClick()
					{
						finish();
						animRightToLeft();
					}

					@Override
					public void onCancelClick()
					{
					}
				}).build().show();
	}
}
